<?php

namespace App\Http\Controllers\Admin;

use Dingo\Api\Http\Response;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Access\AuthorizationException;

class BaseController extends Controller
{
    // 要操作的模型
    public $model;
    // 返回的格式化数据
    public $transformer;
    // 验证规则
    public $validator;

    public function __construct()
    {
        if (empty($this->model) && !class_exists($this->model)) {
            abort('400', '模型实例不存在、请联系网站管理员');
        }
    }

    /**
     * 显示列表方法
     *
     * @param Request|null $request
     * @return Response
     * @throws AuthorizationException
     */
    public function index(Request $request)
    {
        $this->authorize('viewAny', $this->model);

        // 查询数据
        $data = $this->model::pimp()->paginate();

        // 返回数据
        return $this->response->paginator($data, $this->transformer);
    }

    /**
     * 创建新数据方法
     *
     * @param Request $request
     * @return \Illuminate\Http\Response
     * @throws AuthorizationException
     */
    public function store(Request $request)
    {
        $this->authorize('create', $this->model);
        if (!empty($this->validator) && class_exists($this->validator)) {
            resolve($this->validator);
        }

        $id = $this->auth()->user()->id;
        $request->offsetSet('user_id', $id);
        $this->model::create($request->all());

        return $this->response->created();
    }

    /**
     * 显示详情方法
     *
     * @param   $id
     * @return \Illuminate\Http\Response
     * @throws AuthorizationException
     */
    public function show($id)
    {
        $data = $this->model::find($id);

        $this->authorize('view', $data);

        return $this->response->item($data, $this->transformer);
    }

    /**
     * 修改数据方法
     *
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\Response
     * @throws AuthorizationException
     */
    public function update(Request $request, $id)
    {
        if (!empty($this->validator) && class_exists($this->validator)) {
            resolve($this->validator);
        }

        $data = $this->model::find($id);

        $this->authorize('update', $data);

        $data->update($request->all());

        return $this->response->noContent();
    }

    /**
     * 删除数据方法
     *
     * @param int|string $ids
     * @return \Illuminate\Http\Response
     * @throws AuthorizationException
     */
    public function destroy($ids)
    {
        // 获取 id 数组
        $idArr = explode(',', $ids);


        // 获取模型实例
        $data = $this->model::whereIn('id', $idArr)->get();

        if (empty($data)) {
            abort(400, '没有对应的数据');
        }

        foreach ($data as $id) {
            // 检查授权策略
            $this->authorize('delete', $id);
        }
        // 执行删除操作
        $this->model::destroy($idArr);

        return $this->response->noContent();
    }
}
